package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.domain.Category;
import com.itheima.domain.Employee;
import com.itheima.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService  categoryService;

    //新增的
    @PostMapping
    public R<String> save(@RequestBody Category category,
                            HttpSession session){

     /*   category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        //用session得到id
        Long employee = (Long) session.getAttribute("employee");
        category.setCreateUser(employee);
        category.setUpdateUser(employee);*/
        //保存数据
        boolean save = categoryService.save(category);
        //返回成功或者失败信息
        return save?R.success("新增分类成功！"):R.error("保存分类失败");
    }

    //分页
    @GetMapping("/page")
    public R<IPage<Category>> queryPage(Integer page, Integer pageSize){
        //定义当前页和页面大小
        Page<Category> objectPage = new Page<>(page, pageSize);
        //创建一个wrapper
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //以时间降序排序
        wrapper.orderByDesc(Category::getUpdateTime);
        //分页
        categoryService.page(objectPage,wrapper);
        //返回成功的数据
        return R.success(objectPage);
    }

    // 删除
    @DeleteMapping
    public R<String> delete(Long id){
        categoryService.remove(id);

        return R.success("删除成功");
    }

    //修改
    @PutMapping
   public R<String> update(@RequestBody Category category,
                           HttpSession session){
       /* log.info(category.toString());
        category.setUpdateTime(LocalDateTime.now());
        Long id = (Long) session.getAttribute("employee");
        category.setUpdateUser(id);*/
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    @GetMapping("/list")
    public R listCategory(Integer type) {
        //type查询
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(type != null,Category::getType, type);
        //排序
        wrapper.orderByDesc(Category::getUpdateTime);
        //拿到type值
        List<Category> list = categoryService.list(wrapper);
        //返回值
        return R.success(list);
    }

}
